<template>
  <div>
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <main>
      <div class="title">
        <el-input
          placeholder="请输入内容"
          v-model="input3"
          class="input-with-select"
          @keyup.enter.native="search"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="search"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="addUser">添加用户</el-button>
      </div>
      <el-table :data="userList" stripe border>
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              :value="scope.row.mg_state"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              @change="changeState(scope)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="editUser(scope)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteUser(scope)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              size="small"
              @click="changeRole(scope)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </main>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form">
        <el-form-item
          label="用户名"
          label-width="65px"
          prop="username"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
              message: '用户名长度必须为2-11位',
              trigger: ['blur', 'change'],
              pattern: /^.{2,11}$/,
            },
          ]"
        >
          <el-input
            v-model="form.username"
            autocomplete="off"
            :disabled="title === '修改用户'"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="password"
          label="密码"
          label-width="65px"
          v-if="title === '添加用户'"
          :rules="[
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur',
            },
            {
              message: '密码长度不能小于5位',
              trigger: ['blur', 'change'],
              pattern: /^.{5,}$/,
            },
          ]"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="email"
          label="邮箱"
          label-width="65px"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'change'],
              pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
            },
          ]"
        >
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机"
          label-width="65px"
          :rules="[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            {
              message: '请输入正确的手机号码',
              trigger: ['blur', 'change'],
              pattern:
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            },
          ]"
        >
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogRoleVisible">
      <el-form :model="form">
        <el-form-item label="当前的用户:" :label-width="formLabelWidth">
          <span>{{ form.username }}</span>
        </el-form-item>

        <el-form-item label="当前的角色:" :label-width="formLabelWidth">
          <p>{{ form.roleName }}</p>
        </el-form-item>
        <el-form-item label="分配新角色:" :label-width="formLabelWidth">
          <el-select v-model="form.role_name" placeholder="请选择">
            <el-option value="管理员"></el-option>
            <el-option value="wqare"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUserList,
  addUser,
  updateUserStatus,
  deleteUser,
  updateUserInfo,
} from "@/api/user";
import { getRoles, changeRoles } from "@/api/roles";
export default {
  name: "ShopUser",
  data() {
    return {
      currentPage: 1,
      input3: "",
      userList: [],
      userPage: {
        query: "",
        pagenum: "1",
        pagesize: "5",
      },
      total: 0,
      dialogFormVisible: false,
      dialogRoleVisible: false,
      form: {
        id: "",
        username: "",
        email: "",
        mobile: "",
        password: "",
      },
      formLabelWidth: "120px",
      title: "",
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    async getUsers() {
      const res = await getUserList(this.userPage);
      this.userList = res.data.data.users;
      this.total = res.data.data.total;
    },
    search() {
      this.userPage={
        query: this.input3,
        pagenum: "1",
        pagesize: "5",
      }
      this.getUsers();
    },
    addUser() {
      this.title = "添加用户";
      this.form = {
        id: "",
        username: "",
        email: "",
        mobile: "",
        password: "",
      };
      this.dialogFormVisible = true;
    },
    editUser(scope) {
      this.title = "修改用户";
      this.dialogFormVisible = true;
      this.form = scope.row;
    },
    confirmUser() {
      this.$refs["form"].validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请正确填写信息信息");
        } else {
          if (!this.form.id) {
            const res = await addUser({
              username: this.form.username,
              password: this.form.password,
              email: this.form.email,
              mobile: this.form.mobile,
            });
            if (res.data.meta.status === 201) {
              this.$message.success(res.data.meta.msg);
              this.$refs["form"].resetFields();
              this.dialogFormVisible = false;
              this.getUsers();
            } else {
              this.$message.error(res.data.meta.msg);
            }
          } else {
            const res = await updateUserInfo({
              id: this.form.id,
              email: this.form.email,
              mobile: this.form.mobile,
            });
            if (res.data.meta.status === 200) {
              this.$message.success(res.data.meta.msg);
              this.$refs["form"].resetFields();
              this.dialogFormVisible = false;
              this.getUsers();
            } else {
              this.$message.error(res.data.meta.msg);
            }
          }
        }
      });
    },
    deleteUser(scope) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await deleteUser(scope.row.id);
        this.$message.success(res.data.meta.msg);
        this.getUsers();
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        })
      })
    },
    changeRole(scope) {
      // console.log(scope.row);
      this.title = "分配角色";
      this.form = JSON.parse(JSON.stringify(scope.row));
      this.form.roleName = scope.row.role_name;
      this.form.role_name = "";
      this.dialogRoleVisible = true;
    },
    async changeState(scope) {
      console.log(scope);
      const res = await updateUserStatus({
        bool: !scope.row.mg_state,
        id: scope.row.id,
      });
      this.$message.success(res.data.meta.msg);
      this.userList[scope.$index].mg_state = !scope.row.mg_state;
    },
    cancel() {
      this.form = {
        username: "",
        email: "",
        mobile: "",
        password: "",
      };
      this.dialogFormVisible = false;
      this.dialogRoleVisible = false;
    },
    async confirmRole() {
      if (this.form.role_name === "") {
        return this.$message.error("请选择要更改的角色");
      }
      console.log(this.form);
      const res = await changeRoles({
        id: this.form.id,
        rid: this.form.role_name === "管理员" ? 29 : 30,
      });
      if (res.data.meta.status === 400) {
        this.$message.error(res.data.meta.msg);
      } else {
        this.$message.success(res.data.meta.msg);
        this.dialogRoleVisible = false;
      }
    },
    handleSizeChange(val) {
      // console.log(val);
      this.userPage.pagesize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      this.userPage.pagenum = val;
      this.getUsers();
    },
  },
};
</script>
<style lang='less'  scoped>
main {
  width: 100%;
  background-color: #fff;
  margin-top: 15px;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 2px 2px 10px #ccc;
  .title {
    display: flex;
    margin-bottom: 20px;
    .el-input {
      width: 500px;
      margin-right: 20px;
    }
  }
}
.el-form {
  text-align: left;
}
// /deep/.el-form-item__label {
//  text-align-last:justify;
//  text-align:justify
// }
</style>
